//
//  DHCollectionViewController.m
//  Dresshere
//
//  Created by ZhangPeng on 2018/1/11.
//  Copyright © 2018年 张朋. All rights reserved.
//

#import "DHCollectionViewController.h"
#import "FashionArticle.h"
#import "DHFshionWear_SingleCell.h"
#import "DHFashionWear_LargeRectangleCell.h"
#import "DHNewsDetailController.h"
#import "DHProductCollectionViewCell.h"
#import "DHProductDetailViewController.h"
#import "DHCollectionBrandCell.h"
#import "DHS2_BrandViewController.h"

#import "DHBrandProductCollectionCell.h"
#import "DHS2_ProductDetailController.h"
#import "DHSubscription_BrandViewCell.h"
#import "DHMagazine_LargeCell.h"
#import "DHMagazine_NormalCell.h"

@interface DHCollectionViewController ()<UITableViewDelegate, UITableViewDataSource, UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topLineWidthLayout;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topLineLeftLayout;
@property (weak, nonatomic) IBOutlet UIView *topLineView;
@property (weak, nonatomic) IBOutlet UITableView *articleTableView;
@property (weak, nonatomic) IBOutlet UICollectionView *productCollectionView;
@property (weak, nonatomic) IBOutlet UITableView *brandTableView;

@property (strong, nonatomic) NSMutableArray *productArray;
@property (strong, nonatomic) NSMutableArray *brandArray;
@property (strong, nonatomic) NSMutableArray *articleArray;

@property (assign, nonatomic) NSInteger productPageIndex;
@property (assign, nonatomic) NSInteger brandPageIndex;
@property (assign, nonatomic) NSInteger articlePageIndex;

@end

@implementation DHCollectionViewController

- (NSMutableArray *)productArray{
    if (!_productArray) {
        _productArray = [NSMutableArray array];
    }
    return _productArray;
}

- (NSMutableArray *)brandArray{
    if (!_brandArray) {
        _brandArray = [NSMutableArray array];
    }
    return _brandArray;
}

- (NSMutableArray *)articleArray{
    if (!_articleArray) {
        _articleArray = [NSMutableArray array];
    }
    return _articleArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.titleLabel.text = @"我的收藏";
    
    self.topLineWidthLayout.constant = kScreenWidth / 3 - 50;
    self.topLineLeftLayout.constant = 25;
    
    self.productPageIndex = 0;
    self.brandPageIndex = 0;
    self.articlePageIndex = 0;
    
    self.brandTableView.hidden = YES;
    self.articleTableView.hidden = YES;
    
    self.productCollectionView.mj_header = [DHMJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadProductData)];
    self.productCollectionView.mj_footer = [DHMJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreProductData)];
    [self.productCollectionView.mj_header beginRefreshing];
    
    self.brandTableView.mj_header = [DHMJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadBrandData)];
    self.brandTableView.mj_footer = [DHMJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreBrandData)];
    [self.brandTableView.mj_header beginRefreshing];
    
    self.articleTableView.mj_header = [DHMJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadArticleData)];
    self.articleTableView.mj_footer = [DHMJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreArticleData)];
    [self.articleTableView.mj_header beginRefreshing];
    
    [self.articleTableView registerNib:[UINib nibWithNibName:@"DHMagazine_LargeCell" bundle:nil] forCellReuseIdentifier:kDHMagazine_LargeCell];
    [self.articleTableView registerNib:[UINib nibWithNibName:@"DHMagazine_NormalCell" bundle:nil] forCellReuseIdentifier:kDHMagazine_NormalCell];
    
    self.productCollectionView.delegate = self;
    self.productCollectionView.dataSource = self;
    [self.productCollectionView registerNib:[UINib nibWithNibName:@"DHBrandProductCollectionCell" bundle:nil] forCellWithReuseIdentifier:kDHBrandProductCollectionCell];
    
    [self.brandTableView registerNib:[UINib nibWithNibName:@"DHSubscription_BrandViewCell" bundle:nil] forCellReuseIdentifier:kDHSubscription_BrandViewCell];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// 商品
- (IBAction)productAction:(id)sender {
    UIButton *btn = (UIButton *)sender;
    self.productCollectionView.hidden = NO;
    self.brandTableView.hidden = YES;
    self.articleTableView.hidden = YES;
    [UIView animateWithDuration:0.3 animations:^{
        self.topLineLeftLayout.constant = btn.left + 25;
    }];
}

// 品牌
- (IBAction)brandAction:(id)sender {
    UIButton *btn = (UIButton *)sender;
    self.productCollectionView.hidden = YES;
    self.brandTableView.hidden = NO;
    self.articleTableView.hidden = YES;
    [UIView animateWithDuration:0.3 animations:^{
        self.topLineLeftLayout.constant = btn.left + 25;
    }];
}

// 文章
- (IBAction)articleAction:(id)sender {
    UIButton *btn = (UIButton *)sender;
    self.productCollectionView.hidden = YES;
    self.brandTableView.hidden = YES;
    self.articleTableView.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        self.topLineLeftLayout.constant = btn.left + 25;
    }];
}

// 服饰
- (void)loadProductData{
    self.productPageIndex = 0;
    [[DHNetAPIClient shareDHNetAPIClient] request_user_likeParams:@{@"pageIndex":@(self.productPageIndex),@"pageSize":@(20),@"type":@"PRODUCT"} andBlock:^(id data, NSError *error) {
        [self.productCollectionView.mj_header endRefreshing];
        [self.productCollectionView.mj_footer endRefreshing];
        self.productPageIndex += 1;
        [self.productArray removeAllObjects];
        [self.productArray addObjectsFromArray:[data objectForKey:@"collects"]];
        if (self.productArray.count < 20) {
            [self.productCollectionView.mj_footer endRefreshingWithNoMoreData];
        }
        [self.productCollectionView reloadData];
    }];
}

- (void)loadMoreProductData{
    [[DHNetAPIClient shareDHNetAPIClient] request_user_likeParams:@{@"pageIndex":@(self.productPageIndex),@"pageSize":@(20),@"type":@"PRODUCT"} andBlock:^(id data, NSError *error) {
        [self.productCollectionView.mj_header endRefreshing];
        [self.productCollectionView.mj_footer endRefreshing];
        self.productPageIndex += 1;
        [self.productArray addObjectsFromArray:[data objectForKey:@"collects"]];
        if ([[data objectForKey:@"likes"] count] < 20) {
            [self.productCollectionView.mj_footer endRefreshingWithNoMoreData];
        }
        [self.productCollectionView reloadData];
    }];
}

// 品牌
- (void)loadBrandData{
    self.brandPageIndex = 0;
    [[DHNetAPIClient shareDHNetAPIClient] request_user_likeParams:@{@"pageIndex":@(self.brandPageIndex),@"pageSize":@(20),@"type":@"BRAND"} andBlock:^(id data, NSError *error) {
        [self.brandTableView.mj_header endRefreshing];
        [self.brandTableView.mj_footer endRefreshing];
        self.brandPageIndex += 1;
        [self.brandArray removeAllObjects];
        [self.brandArray addObjectsFromArray:[data objectForKey:@"collects"]];
        if (self.brandArray.count < 20) {
            [self.brandTableView.mj_footer endRefreshingWithNoMoreData];
        }
        [self.brandTableView reloadData];
    }];
}
- (void)loadMoreBrandData{
    [[DHNetAPIClient shareDHNetAPIClient] request_user_likeParams:@{@"pageIndex":@(self.brandPageIndex),@"pageSize":@(20),@"type":@"BRAND"} andBlock:^(id data, NSError *error) {
        [self.brandTableView.mj_header endRefreshing];
        [self.brandTableView.mj_footer endRefreshing];
        self.brandPageIndex += 1;
        [self.brandArray addObjectsFromArray:[data objectForKey:@"collects"]];
        if ([[data objectForKey:@"likes"] count] < 20) {
            [self.brandTableView.mj_footer endRefreshingWithNoMoreData];
        }
        [self.brandTableView reloadData];
    }];
}

// 文章
- (void)loadArticleData{
    self.articlePageIndex = 0;
    [[DHNetAPIClient shareDHNetAPIClient] request_user_likeParams:@{@"pageIndex":@(self.articlePageIndex),@"pageSize":@(20),@"type":@"ARTICLE"} andBlock:^(id data, NSError *error) {
        [self.articleTableView.mj_header endRefreshing];
        [self.articleTableView.mj_footer endRefreshing];
        self.articlePageIndex += 1;
        [self.articleArray removeAllObjects];
        [self.articleArray addObjectsFromArray:[data objectForKey:@"collects"]];
        if (self.articleArray.count < 20) {
            [self.articleTableView.mj_footer endRefreshingWithNoMoreData];
        }
        [self.articleTableView reloadData];
    }];
}
- (void)loadMoreArticleData{
    [[DHNetAPIClient shareDHNetAPIClient] request_user_likeParams:@{@"pageIndex":@(self.articlePageIndex),@"pageSize":@(20),@"type":@"ARTICLE"} andBlock:^(id data, NSError *error) {
        [self.articleTableView.mj_header endRefreshing];
        [self.articleTableView.mj_footer endRefreshing];
        self.articlePageIndex += 1;
        [self.articleArray addObjectsFromArray:[data objectForKey:@"collects"]];
        if ([[data objectForKey:@"likes"] count] < 20) {
            [self.articleTableView.mj_footer endRefreshingWithNoMoreData];
        }
        [self.articleTableView reloadData];
    }];
}


#pragma mark - UITableViewDataSource and UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView.tag == 888) {
        return self.articleArray.count;
    }else{
        return self.brandArray.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag == 888) {
        FashionArticle *article = [FashionArticle modelWithDictionary:self.articleArray[indexPath.row]];
        if ([article.layout isEqualToString:@"单行列表"]) {
            return 120;
        }if ([article.layout isEqualToString:@"大矩形"]) {
            return 304;
        }else{
            return 100;
        }
    }else{
        return 63;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag == 888) {
        NSDictionary *model = self.articleArray[indexPath.row];
        if ([[model objectForKey:@"layout"] isEqualToString:@"大矩形"]) {
            DHMagazine_LargeCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHMagazine_LargeCell forIndexPath:indexPath];
            [cell updateCell:model];
            return cell;
        }else{
            DHMagazine_NormalCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHMagazine_NormalCell forIndexPath:indexPath];
            [cell updateCell:model];
            return cell;
        }
    }else{
        DHSubscription_BrandViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHSubscription_BrandViewCell forIndexPath:indexPath];
        NSDictionary *brand = [self.brandArray objectAtIndex:indexPath.row];
        [cell.imgView dh_setImageURLString:[brand objectForKey:@"logo"]];
        cell.nameLabel.text = [brand objectForKey:@"name"];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (tableView.tag == 888) {
        NSDictionary *model = [self.articleArray objectAtIndex:indexPath.row];
        DHNewsDetailController *vc = [[DHNewsDetailController alloc] initWithArticleID:[model objectForKey:@"_id"]];
        [self.navigationController pushViewController:vc animated:YES];
        self.tabBarController.tabBar.hidden = YES;
    }else{
        NSDictionary *brand = [self.brandArray objectAtIndex:indexPath.row];
        DHS2_BrandViewController *brandController = [[DHS2_BrandViewController alloc] initWithBrandID:[brand objectForKey:@"_id"]];
        [self.navigationController pushViewController:brandController animated:YES];
    }
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag == 888) {
        if (editingStyle == UITableViewCellEditingStyleDelete) {
            FashionArticle *article = [FashionArticle modelWithDictionary:self.articleArray[indexPath.row]];
            [[DHNetAPIClient shareDHNetAPIClient] request_user_likeAndOrigin:article._id andBlock:^(id data, NSError *error) {
                [self.articleArray removeObjectAtIndex:indexPath.row];
                [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
                if (self.articleArray.count == 0) {
                    [self.articleTableView.mj_footer endRefreshingWithNoMoreData];
                }
            }];
        }
    }else{
        if (editingStyle == UITableViewCellEditingStyleDelete) {
            NSDictionary *brand = [self.brandArray objectAtIndex:indexPath.row];
            [[DHNetAPIClient shareDHNetAPIClient] request_user_likeAndOrigin:[brand objectForKey:@"_id"] andBlock:^(id data, NSError *error) {
                [self.brandArray removeObjectAtIndex:indexPath.row];
                [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
                if (self.brandArray.count == 0) {
                    [self.brandTableView.mj_footer endRefreshingWithNoMoreData];
                }
            }];
        }
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"取消收藏";
}

#pragma mark - UICollectionViewDataSource and UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (collectionView.tag == 1000) {
        return self.productArray.count;
    }else{
        return self.brandArray.count;
    }
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    DHBrandProductCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kDHBrandProductCollectionCell forIndexPath:indexPath];
    [cell uploadCell:[self.productArray objectAtIndex:indexPath.row]];
    return cell;
}

#pragma mark ---- UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return (CGSize){kScreenWidth/2,317};
}

// 两行之间的最小间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

// 两个cell之间的最小间距，是由API自动计算的，只有当间距小于该值时，cell会进行换行
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *model = [self.productArray objectAtIndex:indexPath.row];
    DHS2_ProductDetailController *vc = [[DHS2_ProductDetailController alloc] initWithProduct:model];
    [self.navigationController pushViewController:vc animated:YES];
}

@end
